package com.chuang.bootplus.config.shiro;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chuang.bootplus.base.utils.BeanUtil;
import com.chuang.bootplus.base.utils.JwtUtil;
import com.chuang.bootplus.config.shiro.JwtToken;
import com.chuang.bootplus.entity.User;
import com.chuang.bootplus.service.UserService;
import com.chuang.bootplus.vo.UserInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: lhy
 * 自定义Realm
 */
@Slf4j
@Component
public class AccountRealm extends AuthorizingRealm {
    @Autowired
    JwtUtil jwtUtils;
    @Autowired
    UserService userService;
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        return null;
    }
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        JwtToken jwt = (JwtToken) token;
        log.info("jwt----------------->{}", jwt);
        String userId = jwtUtils.getClaimByToken((String) jwt.getPrincipal()).getSubject();
        User user = userService.getById(Long.parseLong(userId));
        if(user == null) {
            throw new UnknownAccountException("账户不存在！");
        }
        UserInfoVO userInfoVO = BeanUtil.beanA2beanB(user, UserInfoVO.class);
        log.info("profile----------------->{}", userInfoVO.toString());
        return new SimpleAuthenticationInfo(userInfoVO, jwt.getCredentials(), getName());
    }
}
